package com.wendyxie.sproutup.view

import com.wendyxie.sproutup.view.adapter.ScoreTmplAdapter
import android.content.Intent
import android.os.Bundle
import androidx.appcompat.app.AppCompatActivity
import androidx.recyclerview.widget.ItemTouchHelper
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.wendyxie.sproutup.databinding.ActivityParentSettingBinding
import com.wendyxie.sproutup.db.SQLInitHelper
import com.wendyxie.sproutup.db.SQLUserScoreTmplHelper


class ParentSettingActivity : AppCompatActivity() {
    private lateinit var binding: ActivityParentSettingBinding
    private lateinit var scoreTmplAdapter: ScoreTmplAdapter

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        binding = ActivityParentSettingBinding.inflate(layoutInflater)
        setContentView(binding.root)
        // 初始化列表
        scoreTmplAdapter = ScoreTmplAdapter()
        binding.listItem.layoutManager = LinearLayoutManager(this)
        binding.listItem.adapter = scoreTmplAdapter
        // 设置列表：滑动删除功能
        val itemTouchHelper = ItemTouchHelper(object : ItemTouchHelper.SimpleCallback(0, ItemTouchHelper.LEFT) {
            override fun onMove(
                recyclerView: RecyclerView,
                viewHolder: RecyclerView.ViewHolder,
                target: RecyclerView.ViewHolder
            ): Boolean {
                return false // 不允许拖动
            }

            override fun onSwiped(viewHolder: RecyclerView.ViewHolder, direction: Int) {
                val position = viewHolder.adapterPosition
                scoreTmplAdapter.removeItem(position) // 删除数据并更新UI
            }
        })
        itemTouchHelper.attachToRecyclerView(binding.listItem);

        // 3. 点击添加按钮，跳转到添加页面
        binding.btnAdd.setOnClickListener {
            val intent = Intent(this, AddScoreTmplActivity::class.java)
            startActivity(intent)
        }
    }

    override fun onResume() {
        super.onResume()
        // 从数据库中取出 设定的列表
        val tmplList = SQLUserScoreTmplHelper.getUserScoreTmplList(10, 0, SQLInitHelper(this).openDatabase());
        scoreTmplAdapter.setItems(tmplList)
    }
}
